import logging
import sys
from collections import Counter
from datetime import datetime
from urllib.parse import urlsplit
from clickhouse_driver import Client
import json
import pandas as pd
import requests
from gen_info_dic import gen_info_dic
from get_response import gen_wafermap_config
from get_sql_res import gen_run_detail


def gen_part_wafermapconfig(info_dic, sql_info):
    df_config = gen_wafermap_config(info_dic, sql_info)['data']
    df_config = pd.DataFrame(df_config)
    int_columns = df_config.select_dtypes(
        include='int64').columns
    df_config[int_columns] = df_config[int_columns].astype(
        float)
    waferMapConfig = {
        "mode": "config",
        "ws": df_config['waferDiameter'].iloc[0],
        "wf": df_config['notch'].iloc[0],
        "px": df_config['posX'].iloc[0],
        "py": df_config['posY'].iloc[0],
        "rr": df_config['reticleRow'].iloc[0],
        "dh": df_config['dieHeight'].iloc[0],
        "crx": df_config['centerReticleX'].iloc[0],
        "cry": df_config['centerReticleY'].iloc[0],
        "coy": df_config['centerDieOffsetX'].iloc[0],
        "cox": df_config['centerDieOffsetY'].iloc[0],
        "rc": df_config['reticleColumn'].iloc[0],
        "dw": df_config['dieWidth'].iloc[0],
        "cx": df_config['centerDieX'].iloc[0],
        "wm": df_config['waferMargin'].iloc[0],
        "cy": df_config['centerDieY'].iloc[0],
        "rcco": df_config['reticleColumnCenterOffset'].iloc[0],
        "crox": df_config['centerReticleOffsetX'].iloc[0],
        "croy": df_config['centerReticleOffsetY'].iloc[0],
        "rrco": df_config['reticleRowCenterOffset'].iloc[0]
    }
    return waferMapConfig


def gen_part_data(result_id, sql_info):
    ck_conn = Client(
        host=sql_info['ckInfo']['onedata']['host'],
        port=sql_info['ckInfo']['onedata']['port'],
        user=sql_info['ckInfo']['onedata']['user'],
        password=sql_info['ckInfo']['onedata']['password'])
    data_base = sql_info['ckInfo']['onedata']['db']
    sql = f'''
            select *
            from {data_base}.rule_result_data_cluster
            where RESULT_ID={result_id}
            and DATA_TYPE='OUTPUT';
            '''
    df_data_cluster = ck_conn.query_dataframe(sql)

    def gen_dic_for_legend(df_data):
        try:
            dic_for_legend_alg = dict(Counter(df_data['hitAlg'].dropna()))
        except BaseException:
            dic_for_legend_alg = {}
        dic_for_legend_PF = {
            'P': Counter(df_data[df_data['algHitFlag'] == False]['hbinPf'])['P'],
            'F': Counter(df_data[df_data['algHitFlag'] == False]['hbinPf'])['F'],
            'total': sum(Counter(df_data['hbinPf']).values())
        }
        return dic_for_legend_PF, dic_for_legend_alg

    # 获取DATA字段中的json字符串并转化为字典
    data = json.loads(df_data_cluster.iloc[0]['DATA'])
    df_dieOutputDTOList = pd.DataFrame(data['data']['dieOutputDTOList'])
    res_df = pd.DataFrame()
    res_df['tmp'] = df_dieOutputDTOList['algHitFlag']
    res_df['k'] = df_dieOutputDTOList.apply(
        lambda row: f"F-HBIN999-{row['hitAlg']}" if row['algHitFlag'] else row['hbinPf'],
        axis=1)
    # res_df.loc[res_df['tmp'], 'k'] = f"F-HBIN999-{row['hitAlg']}"
    res_df['x'] = df_dieOutputDTOList['x']
    res_df['y'] = df_dieOutputDTOList['y']
    res_df['rx'] = 0
    res_df['ry'] = 0
    res_df['hl'] = 0
    res_df['e'] = df_dieOutputDTOList['ecid']
    res_df['v'] = df_dieOutputDTOList['hbinPf']
    res_df.loc[res_df['tmp'], 'v'] = 'F'
    data_df = res_df.drop('tmp', axis=1)
    data = json.loads(data_df.to_json(orient='records'))  # 列表
    dic_for_legend_PF, dic_for_legend_alg = gen_dic_for_legend(df_dieOutputDTOList)
    return data, dic_for_legend_PF, dic_for_legend_alg


def gen_part_legend(dic_for_legend_PF, dic_for_legend_alg, total_cnt):

    legend_lst = [{
        "k": "P",
        "name": "Pass",
        "count": dic_for_legend_PF['P'],
        "percent": round(dic_for_legend_PF['P'] / total_cnt, 4),
        "hitAlg": 0,
        "pf": "P"
    }, {
        "k": "F",
        "name": "Fail",
        "count": dic_for_legend_PF['F'],
        "percent": round(dic_for_legend_PF['F'] / total_cnt, 4),
        "hitAlg": 0,
        "pf": "F"
    }]
    if len(dic_for_legend_alg) != 0:
        for k in sorted(dic_for_legend_alg.keys()):
            v=dic_for_legend_alg[k]
            dic = {}
            dic["k"] = f"F-HBIN999-{k}"
            dic["name"] = f"F-HBIN999-{k}"
            dic["count"] =v
            dic["percent"] = round(v / total_cnt, 4)
            dic["hitAlg"] = 1
            dic["pf"] = "F"
            legend_lst.append(dic)
    legend = {
        "firstColumnName": "Result",
        "data": legend_lst
    }
    return legend


def gen_single_fig(result_id, info_dic, sql_info, wafer_id):
    # part_wafermapconfig
    waferMapConfig = gen_part_wafermapconfig(info_dic, sql_info)

    # part_data
    data, dic_for_legend_PF, dic_for_legend_alg = gen_part_data(
        result_id, sql_info)

    # part_lengend
    total_cnt = dic_for_legend_PF['total']
    legend = gen_part_legend(dic_for_legend_PF, dic_for_legend_alg, total_cnt)

    # summary
    summary = [
        {
            "label": "Test Stage",
            "value": info_dic['test_stage']
        },
        {
            "label": "Lot ID",
            "value": info_dic['Lot ID']
        },
        {
            "label": "Wafer ID",
            "value": wafer_id
        },
        {
            "label": "Total Count",
            "value": total_cnt
        }
    ]

    # setting
    setting = {
        "showType": "LEGEND",
        "standard": 1,
        "theme": "PF",
        "showSite": 0,
        "showAxis": 1,
        "showReticle": 0
    }

    # 汇总为request_data_dic
    request_data_dic = {
        "appKey": "rule",
        "chartType": "WAFER_MAP",
        "data": {
            'data': data,
            'waferMapConfig': waferMapConfig,
            'legend': legend,
            'summary': summary,
            'setting': setting
        },
        "exportType": "PNG"
    }

    # 请求path
    url = sql_info['reportHost']
    url = url + '/report/image/generate'
    headers = {'Content-Type': 'application/json'}
    response = requests.post(url, headers=headers, json=request_data_dic)
    response = json.loads(response.text)  # 字典
    path = response['data']
    return path


def gen_figs(df_run_detail,info_dic,sql_info):
    path_dic = {}
    result_ids = list(df_run_detail['id'])
    for result_id in result_ids:
        wafer_id = df_run_detail[df_run_detail['id']
                                 == result_id]['wafer_id'].iloc[0]
        rule_name = df_run_detail[df_run_detail['id']
                                  == result_id]['rule_alias'].iloc[0]
        result_status=df_run_detail[df_run_detail['id']
                                  == result_id]['result_status'].iloc[0]
        if result_status== 'PASS':
            path = gen_single_fig(result_id, info_dic, sql_info, wafer_id)
        else:
            path=''

        if wafer_id not in path_dic:
            path_dic[wafer_id] = {rule_name:path}
        else:
            path_dic[wafer_id][rule_name] = path
    return path_dic
